<template>
  <a-modal
    :open="visible"
    title="换房"
    width="500px"
    @ok="handleOk"
    @cancel="handleCancel"
    @update:open="(val) => emit('update:visible', val)"
  >
    <a-form :model="formData" :rules="rules" ref="formRef" layout="vertical">
      <a-form-item label="原房间号" name="oldRoomNumber">
        <a-input v-model:value="formData.oldRoomNumber" disabled />
      </a-form-item>

      <a-form-item label="目标房间号" name="newRoomNumber">
        <a-select
          v-model:value="formData.newRoomNumber"
          placeholder="请选择目标房间"
          show-search
          :filter-option="filterOption"
        >
          <a-select-option
            v-for="room in availableRooms"
            :key="room.number"
            :value="room.number"
          >
            {{ room.number }} ({{ room.type }})
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="换房原因" name="reason">
        <a-textarea
          v-model:value="formData.reason"
          placeholder="请输入换房原因"
          :rows="3"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { message } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';

interface Room {
  id: string;
  number: string;
  type: string;
  status: string;
  capacity: number;
  occupied: number;
}

interface Props {
  visible: boolean;
  room?: Room | null;
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const formRef = ref<FormInstance>();
const formData = ref({
  oldRoomNumber: '',
  newRoomNumber: '',
  reason: '',
});

// 模拟可用房间数据
const availableRooms = ref<Room[]>([
  {
    id: '1',
    number: '1001',
    type: '休息室',
    status: 'vacant',
    capacity: 5,
    occupied: 0,
  },
  {
    id: '2',
    number: '1002',
    type: '休息室',
    status: 'vacant',
    capacity: 5,
    occupied: 0,
  },
  {
    id: '3',
    number: '2001',
    type: '棋牌室',
    status: 'vacant',
    capacity: 4,
    occupied: 0,
  },
  {
    id: '4',
    number: '3001',
    type: 'VIP休息室',
    status: 'vacant',
    capacity: 6,
    occupied: 0,
  },
]);

const rules = {
  newRoomNumber: [{ required: true, message: '请选择目标房间' }],
};

// 监听房间变化
watch(
  () => props.room,
  (room) => {
    if (room) {
      formData.value = {
        oldRoomNumber: room.number,
        newRoomNumber: '',
        reason: '',
      };
    }
  },
  { immediate: true },
);

const filterOption = (input: string, option: any) => {
  return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

const handleOk = async () => {
  try {
    await formRef.value?.validate();

    // 这里调用换房API
    message.success('换房成功');
    emit('update:visible', false);
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleCancel = () => {
  emit('update:visible', false);
};
</script>
